import uuid
import pickle
from config import cfg

class Session(object):
    def __init__(self):
        self._sessionid = uuid.uuid4().hex
        self.cache = {}

    def set(self, key, value):
        self.cache[key] = value

    def get(self, key, default=None):
        return self.cache.get(key, default)

    def clear(self):
        self.cache.clear()

    @property
    def sessionid(self):
        return self._sessionid

    def serialization(self):
        return pickle.dumps(self)

    @staticmethod
    def deserialization(str):
        return pickle.loads(str)

# 序列化后的保存机制
import redis
class SessionManger(object):
      conn = redis.Redis(**cfg['redis'])
      test = conn.ping()
      # 类方法做工具
      @classmethod
      def cache2redis(cls, sessionobj):
          cls.conn.set(sessionobj.sessionid, sessionobj.serialization(), ex=14*24*60*60)

      @classmethod
      def getSessionObjBySid(cls, sessionid):
          sessionobj = Session.deserialization(cls.conn.get(sessionid)) if cls.conn.get(sessionid) else None

          if not sessionobj:
              sessionobj = Session()
          return sessionobj

